package com.cdvtc.flower.dao.impl;

import com.cdvtc.flower.dao.OrderDao;
import com.cdvtc.flower.model.Order;
import com.cdvtc.flower.model.Orderdetail;
import com.cdvtc.flower.model.Products;
import com.cdvtc.flower.util.DBUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OrderDaoImpl implements OrderDao { // 建议将类名更改为 FlowerDaoImpl 或 ProductDaoImpl

    // 如果这个连接字段在其他地方也被使用，请保留它。否则，可以从类中移除它。  
    // private Connection conn; // 这个字段可能不再需要，除非你在其他地方使用它
    @Override
    public List<Order> getAllorders() { // 方法名已更改为遵循Java命名约定
        List<Order> orders = new ArrayList<>();

        try (Connection conn = DBUtil.getConnection(); // 使用try-with-resources自动关闭连接
             Statement st = conn.createStatement(); // 使用try-with-resources自动关闭Statement
             ResultSet rs = st.executeQuery("SELECT   od.product_id,od.quantity,od.order_id,  o.customer_id,   o.order_date_time,  o.total_price,   o.review " +
                     "FROM  `order` o    " +
                     "INNER JOIN  orderdetails od " +
                     "ON o.order_id = od.order_id;")) { // 查询所有产品

            // 从rs中获取数据
            while (rs.next()) {
//                int order_detail_id = rs.getInt("order_detail_id");
                int order_id = rs.getInt("order_id");
                int quantity = rs.getInt("quantity");
                int product_id = rs.getInt("product_id");
                int customer_id = rs.getInt("customer_id");
                Date order_date_time = rs.getDate("order_date_time");
                BigDecimal total_price = rs.getBigDecimal("total_price");
                String review = rs.getString("review");



                // 将数据写入封装对象
                Order order = new Order();
                order.setProduct_id(product_id); // 假设set方法遵循JavaBean规范
                order.setOrder_id(order_id);
//                order.setOrder_detail_id(order_detail_id);
                order.setQuantity(quantity);
                order.setOrder_id(order_id); // 假设set方法遵循JavaBean规范
                order.setCustomer_id(customer_id);
                order.setOrder_date_time(order_date_time);
                order.setTotal_price(total_price);
                order.setReview(review);
                orders.add(order); // 将产品添加到列表中
            }

        } catch (SQLException e) {
            // 处理数据库相关的异常
            e.printStackTrace(); // 这只是暂时的，你应该使用更合适的日志记录方法
            // 可以在这里抛出异常或返回一个空的列表，具体取决于你的应用需求
        }

        return orders; // 返回产品列表
    }

    @Override
    public Order getOrderById(int order_id) {
        Order order= null;
        try (Connection conn = DBUtil.getConnection(); // 使用try-with-resources自动关闭连接
             PreparedStatement pstmt = conn.prepareStatement("SELECT " +
                     "od.product_id, od.quantity, od.order_detail_id, od.order_id, " +
                     "o.customer_id, o.order_date_time, o.total_price,o.review " +
                     "FROM `order` o " +
                     "INNER JOIN orderdetails od ON o.order_id = od.order_id " +
                     "WHERE o.order_id = ?")) {

            pstmt.setInt(1, order_id); // 设置参数

            try (ResultSet rs = pstmt.executeQuery()) { // 查询数据库
                if (rs.next()) { // 如果有结果
                    // 从rs中获取数据
                    int product_id = rs.getInt("product_id");
                    int order_detail_id = rs.getInt("order_detail_id");
                    int customer_id = rs.getInt("customer_id");
                    Date order_date_time = rs.getDate("order_date_time");
                    int quantity = rs.getInt("quantity");
                    BigDecimal total_price = rs.getBigDecimal("total_price");
                    String view = rs.getString("review");
                    // 将数据写入封装对象
                    order = new Order();
                    order.setProduct_id(product_id); // 设置ID，因为我们已经有了这个值
                    order.setOrder_detail_id(order_detail_id);
                    order.setQuantity(quantity);
                    order.setOrder_id(order_id);
                    order.setReview(view);
                    order.setTotal_price(total_price);
                    order.setCustomer_id(customer_id);
                    order.setOrder_date_time(order_date_time);
                }
            }
        } catch (SQLException e) {
            // 处理数据库相关的异常
            e.printStackTrace(); // 这只是暂时的，你应该使用更合适的日志记录方法
            // 可以在这里抛出异常或返回null，具体取决于你的应用需求
        }
        return order; // 返回找到的产品，如果没有找到则返回null
    }


    @Override
    public void updateOrder(Order order) {
        try (Connection conn = DBUtil.getConnection(); // 使用try-with-resources自动关闭连接
             PreparedStatement pstmt = conn.prepareStatement(
                     "UPDATE `order` SET customer_id = ?,order_date_time = ?, total_price = ?,review = ? " +
                             "WHERE order_id = ?")) { // 准备SQL语句以更新产品

            // 设置更新的字段值
            pstmt.setInt(1, order.getCustomer_id());
            pstmt.setDate(2,new java.sql.Date(order.getOrder_date_time().getTime()));
            pstmt.setBigDecimal(3, order.getTotal_price());
            pstmt.setString(4, order.getReview());
            // 设置WHERE子句中的产品ID
            pstmt.setInt(5, order.getOrder_id());

            // 执行更新
            pstmt.executeUpdate();

        } catch (SQLException e) {
            // 处理数据库相关的异常
            e.printStackTrace(); // 这只是暂时的，你应该使用更合适的日志记录方法
            // 在这里你可以抛出异常或进行其他错误处理
        }
    }
    @Override
    public String DeleteOrder(int order_id) {
        String message = "";

        try (Connection conn = DBUtil.getConnection()) {
            // 开启事务
            conn.setAutoCommit(false);

            try {
                // 删除orderdetails表中与order_id相关的记录
                String deleteDetailsSql = "DELETE FROM orderdetails WHERE order_id = ?";
                try (PreparedStatement deleteDetailsStmt = conn.prepareStatement(deleteDetailsSql)) {
                    deleteDetailsStmt.setInt(1, order_id);
                    int detailsRowsAffected = deleteDetailsStmt.executeUpdate();

                    // 删除order表中与order_id相关的记录
                    String deleteOrderSql = "DELETE FROM `order` WHERE order_id = ?";
                    try (PreparedStatement deleteOrderStmt = conn.prepareStatement(deleteOrderSql)) {
                        deleteOrderStmt.setInt(1, order_id);
                        int orderRowsAffected = deleteOrderStmt.executeUpdate();

                        // 检查是否成功删除了记录
                        if (detailsRowsAffected >= 0 && orderRowsAffected == 1) {
                            message = "订单及明细删除成功！";
                        } else {
                            message = "订单或明细删除失败，请检查数据！";
                        }
                    }
                }

                // 提交事务
                conn.commit();
            } catch (SQLException e) {
                // 发生异常，回滚事务
                conn.rollback();
                // 处理数据库相关的异常
                e.printStackTrace(); // 替换为更合适的日志记录方法
                message = "删除订单时发生错误，请稍后再试！";
            } finally {
                // 恢复自动提交模式
                conn.setAutoCommit(true);
            }
        } catch (SQLException e) {
            // 处理获取连接时的异常
            e.printStackTrace(); // 替换为更合适的日志记录方法
            message = "获取数据库连接时发生错误，请稍后再试！";
        }

        return message; // 返回删除操作的结果消息
    }
    private Connection conn;

    @Override
    public boolean insertOrder(Order order) {
        System.out.println(order);
        boolean result = false;

        conn = DBUtil.getConnection();

//        Savepoint savepoint1 = null; // 定义保存点
        // 增加订单表
        try {
            conn.setAutoCommit(false); // 关闭自动提交（默认为打开）
//            savepoint1 = con.setSavepoint("Savepoint1"); // 获取保存点


            String query = "insert into `order` (customer_id, order_date_time, total_price, review) values(?,?,?,?)";
            PreparedStatement pst = this.conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);  //注意需要返回自动生成主键：订单编号
            pst.setInt(1, order.getCustomer().getCustomer_id());
            pst.setTimestamp(2, new Timestamp(new java.util.Date().getTime()));
            // 计算总金额
            BigDecimal total = BigDecimal.ZERO;
            for (Orderdetail orderdetail : order.getOrderdetailList()) {
                total = total.add(orderdetail.getTotal_price()); //累加汇总
            }
            String b ="一般";

            pst.setBigDecimal(3, total);
            pst.setString(4,  b); // 设置订单状态为1
            pst.executeUpdate();

            ResultSet rs = pst.getGeneratedKeys();  // 获取订单编号
            rs.next();
            int order_id = rs.getInt(1);
            System.out.println(order_id);
            // 增加订单明细表
            for (Orderdetail orderdetail : order.getOrderdetailList()) {
                insertOrderItem(order_id, orderdetail);
            }
            result = true;

            conn.commit(); //提交（确保数据存库）
        } catch (SQLException e) {
            System.out.println(e.getMessage());
            try {
//                con.rollback(savepoint1);  //回滚（退回订单生成前状态）
                conn.rollback(); //回滚（退回订单生成前状态）
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                conn.setAutoCommit(true); // 恢复自动提交
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


@Override
    public List<Order> customerOrders(int customer_id) {
        List<Order> list = new ArrayList<>();
    System.out.println("123:"+customer_id);
        try {
            conn = DBUtil.getConnection();
            String query = "select * from `order` where customer_id=?  and review='一般' order by order_id desc";
            PreparedStatement pst = conn.prepareStatement(query);
            pst.setInt(1, customer_id);
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                Order orderList = new Order();

                int orderId = rs.getInt("order_id");
                orderList.setOrder_id(orderId);
                orderList.setTotal_price(rs.getBigDecimal("total_price"));
                orderList.setOrder_date_time(rs.getTimestamp("order_date_time"));
                orderList.setOrderdetailList(getOrderdetailList(orderId));
                System.out.println(orderList);
                list.add(orderList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return list;
    }

@Override
    public void cancelOrder(int order_id) {
        //boolean result = false;
        try {
            conn = DBUtil.getConnection();
            String query = "update `order` set review ='不想要了' where order_id=?"; // 訂單狀態設置為取消狀態-1
            PreparedStatement pst = conn.prepareStatement(query);
            pst.setInt(1, order_id);
            pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.print(e.getMessage());
        }
    }
    @Override
public List<Orderdetail> getOrderdetailList(int order_id) {
        List<Orderdetail> orderItems = new ArrayList<>();
        try {
            String query = "select * from orderdetails left join products on products.product_id=orderdetails.product_id where order_id=?";
            PreparedStatement pst = this.conn.prepareStatement(query);
            pst.setInt(1, order_id);
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                Orderdetail orderItem = new Orderdetail();

                orderItem.setSale_price(rs.getBigDecimal("sale_price"));
                orderItem.setQuantity(rs.getInt("quantity"));
                orderItem.setOrder_detail_id(rs.getInt("order_detail_id"));

                Products product = new Products();
                product.setProduct_name(rs.getString("product_name"));
                product.setImage(rs.getString("image"));
                product.setProduct_id(rs.getInt("product_id"));

                orderItem.setProduct(product);

                orderItems.add(orderItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

        return orderItems;
    }
    /**
     * 增加一项订单明细
     *
     * @param order_id
     * @param orderdetail
     */

@Override
public void insertOrderItem(int order_id, Orderdetail orderdetail) throws SQLException {
        PreparedStatement pst = this.conn.prepareStatement("insert into `orderdetails` ( product_id,order_id, quantity,sale_price) values(?,?,?,?)");
        pst.setInt(1, orderdetail.getProduct().getProduct_id());
        pst.setInt(2, order_id);
        pst.setInt(3, orderdetail.getQuantity());
        pst.setBigDecimal(4,orderdetail.getSale_price());

        pst.executeUpdate();
    }
    public static void main(String[] args) {
        OrderDao orderDao = new OrderDaoImpl();
        System.out.println(orderDao.getOrderById(1));
    }
}